package com.zbkj.crmeb.chant.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.constants.Constants;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.RedisUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.DateUtil;
import com.zbkj.crmeb.chant.dao.ChannelMerchantExperienceDao;
import com.zbkj.crmeb.chant.dto.ChannelMerchantDTO;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.model.ChannelMerchantExperience;
import com.zbkj.crmeb.chant.model.ChannelMerchantRenewal;
import com.zbkj.crmeb.chant.request.AddRenewalRequest;
import com.zbkj.crmeb.chant.request.ChannelMerchantExperienceRequest;
import com.zbkj.crmeb.chant.response.ChannelMerchantExperienceResponse;
import com.zbkj.crmeb.chant.service.ChannelMerchantExperienceService;
import com.zbkj.crmeb.chant.service.ChannelMerchantRenewalService;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.DeliveryTypeEnum;
import com.zbkj.crmeb.enums.RoleEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.enums.StoreEnum;
import com.zbkj.crmeb.system.model.SystemAdmin;
import com.zbkj.crmeb.system.service.SystemAdminService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ChannelMerchantExperienceServiceImpl extends ServiceImpl<ChannelMerchantExperienceDao, ChannelMerchantExperience> implements ChannelMerchantExperienceService {

    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private ICategoryMatchService categoryMatchService;
    @Autowired
    private ChannelMerchantRenewalService channelMerchantRenewalService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 功能描述: 保存注册信息
     * @Param: [request]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2023/4/24 16:50
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CrmebException.class})
    @Override
    public Boolean saveInfo(ChannelMerchantExperienceRequest request) {
        ChannelMerchantExperience one = this.getOne(Wrappers.<ChannelMerchantExperience>lambdaQuery().eq(ChannelMerchantExperience::getCompanyName, request.getCompanyName()));
        if (Objects.nonNull(one)) {
            throw new CrmebException("该公司已经注册");
        }
        // 保存注册信息
        ChannelMerchantExperience channelMerchantExperience = new ChannelMerchantExperience();
        BeanUtils.copyProperties(request, channelMerchantExperience);
        channelMerchantExperience.setDeliveryType(request.getDeliveryType().toString());
        boolean save = this.save(channelMerchantExperience);

        // 生成对应商户信息
        ChannelMerchantDTO channelMerchantDTO = new ChannelMerchantDTO();
        channelMerchantDTO.setChannelType(2);
        channelMerchantDTO.setChannelName(request.getCompanyName());
        channelMerchantDTO.setContactPerson(request.getRealName());
        channelMerchantDTO.setContactPhone(request.getPhone());
        channelMerchantDTO.setDetail(request.getDetail());
        channelMerchantDTO.setAgentType(0);
        channelMerchantDTO.setAgentId(0);
        channelMerchantDTO.setIndexConfig(1);
        channelMerchantDTO.setProductDetailConfig(1);
        channelMerchantDTO.setIsEurope(0);
        channelMerchantDTO.setAppletType(1);
        channelMerchantDTO.setShowSupplier(0);
        channelMerchantDTO.setShowDiscount(1);
        channelMerchantDTO.setAutomaticShelves(1);
        channelMerchantDTO.setIsRegister(true);
        channelMerchantDTO.setBrandIds("[]");
        channelMerchantDTO.setSuppliersIds("[]");
        channelMerchantDTO.setTempId(StockAreaTempEnum.listValue().toString());
        channelMerchantDTO.setProductType(RoleEnum.EXPERIENCE.getCode());
        CommonResult<String> commonResult = channelMerchantService.addMerchant(channelMerchantDTO);

        // 给注册账号赋予商户id
        String data = commonResult.getData();
        boolean update = systemAdminService.update(Wrappers.<SystemAdmin>lambdaUpdate().eq(SystemAdmin::getId, request.getAdminId())
                .set(SystemAdmin::getMerId, "[" + data + "]"));
        channelMerchantExperience.setMerId(Integer.parseInt(data));
        return this.updateById(channelMerchantExperience) && save && commonResult.getCode() == 200 && update;
    }

    /**
     * 功能描述: 体验商户列表
     * @Param: [request]
     * @Return: java.util.List<com.zbkj.crmeb.chant.response.ChannelMerchantExperienceResponse>
     * @Author: wangzh
     * @Date: 2023/4/25 16:32
     */
    @Override
    public CommonPage<ChannelMerchantExperienceResponse> getList(ChannelMerchantExperienceRequest request) {
        LambdaQueryWrapper<ChannelMerchantExperience> queryWrapper = new LambdaQueryWrapper<>();
        List<ChannelMerchantExperienceResponse> responses = new ArrayList<>();
        // 手机号模糊搜索
        if (Objects.nonNull(request.getPhone())) {
            queryWrapper.like(ChannelMerchantExperience::getPhone, request.getPhone());
        }
        // 姓名模糊搜索
        if (Objects.nonNull(request.getRealName())) {
            queryWrapper.like(ChannelMerchantExperience::getRealName, request.getRealName());
        }
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getLimit());
        queryWrapper.orderByDesc(ChannelMerchantExperience::getId);
        List<ChannelMerchantExperience> channelMerchantExperiences = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(channelMerchantExperiences)) {
            return CommonPage.restPage(responses);
        }
        List<Integer> cateIds = channelMerchantExperiences.stream().map(ChannelMerchantExperience::getMainCategory).distinct().collect(Collectors.toList());
        Map<Integer, CategoryMatch> categoryMatchMap = categoryMatchService.listByIds(cateIds).stream().collect(Collectors.toMap(CategoryMatch::getId, e -> e, (v1, v2) -> v2));
        for (ChannelMerchantExperience channelMerchantExperience : channelMerchantExperiences) {
            ChannelMerchantExperienceResponse response = new ChannelMerchantExperienceResponse();
            BeanUtils.copyProperties(channelMerchantExperience, response);
            // 固定类型，后续变更时，使用枚举类型
            response.setIdentityType("渠道商户");
            response.setMainCategory(categoryMatchMap.get(channelMerchantExperience.getMainCategory()).getName());
            response.setStore(StoreEnum.getMsgByCode(channelMerchantExperience.getStore()).getMsg());
            StringBuilder stringBuilder = new StringBuilder();

            for (Object deliveryType : JSONArray.parseArray(channelMerchantExperience.getDeliveryType())) {
                stringBuilder.append(DeliveryTypeEnum.getMsgByCode((Integer) deliveryType).getMsg());
                stringBuilder.append(",");
            }
            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(","));
            response.setDeliveryType(stringBuilder.toString());
            response.setCreateTime(DateUtil.dateToStr(channelMerchantExperience.getCreateTime(), Constants.DATE_FORMAT));
            responses.add(response);
        }

        return CommonPage.restPage(CommonPage.copyPageInfo(page, responses));
    }

    @Transactional(rollbackFor = {Error.class, Exception.class, CrmebException.class})
    @Override
    public Boolean changeExperienceType(Integer merId, Integer productType, Boolean flag) {
        // 生成商户续费1年记录
        AddRenewalRequest request = new AddRenewalRequest();
        request.setMerId(merId);
        request.setPrice(RoleEnum.getEnumByCode(productType).getPrice());
        // 到期时间
        LocalDateTime expirationTime = LocalDateTime.now().plusYears(1);
        ChannelMerchantRenewal merchantRenewal = channelMerchantRenewalService.getOne(Wrappers.<ChannelMerchantRenewal>lambdaQuery().eq(ChannelMerchantRenewal::getMerId, request.getMerId()).orderByDesc(ChannelMerchantRenewal::getExpirationTime).last("LIMIT 1"));
        if (merchantRenewal != null){
            expirationTime = merchantRenewal.getExpirationTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().plusYears(1);
        }
        request.setExpirationTime(Date.from(expirationTime.atZone(ZoneId.systemDefault()).toInstant()));
        request.setFlag(flag);
        channelMerchantRenewalService.addRenewal(request);
        // 商户产品类型变更
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        channelMerchant.setProductType(productType);
        boolean update = channelMerchantService.updateById(channelMerchant);
        if (update) {
            redisUtil.set(Constants.CHANNEL_MERCHANT + channelMerchant.getId(),channelMerchant,24L, TimeUnit.HOURS);
        }
        // 主账号权限角色变更
        channelMerchantService.updateAccountRole(productType, "["+ merId +"]");
        if (!flag) {
            // 操作管理员添加所属商户
            channelMerchantService.addMerId(merId);
        }
        return update;
    }
}
